3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
33 * Base class for file repositories
38 const DELETE_SOURCE
= 1;
40 const OVERWRITE_SAME
= 4;
41 const SKIP_LOCKING
= 8;
43 /** @var FileBackend */
45 /** @var Array Map of zones to config */
46 protected $zones = array();
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
56 * Factory functions for creating new files
57 * Override these in the base class
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
64 * @param $info array|null
67 function __construct( array $info = null ) {
68 // Verify required settings presence
71 ||
!array_key_exists( 'name', $info )
72 ||
!array_key_exists( 'backend', $info )
74 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
78 $this->name
= $info['name'];
79 if ( $info['backend'] instanceof FileBackend
) {
80 $this->backend
= $info['backend']; // useful for testing
82 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
85 // Optional settings that can have no value
86 $optionalSettings = array(
87 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
88 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
91 foreach ( $optionalSettings as $var ) {
92 if ( isset( $info[$var] ) ) {
93 $this->$var = $info[$var];
97 // Optional settings that have a default
98 $this->initialCapital
= isset( $info['initialCapital'] )
99 ?
$info['initialCapital']
100 : MWNamespace
::isCapitalized( NS_FILE
);
101 $this->url
= isset( $info['url'] )
103 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
104 if ( isset( $info['thumbUrl'] ) ) {
105 $this->thumbUrl
= $info['thumbUrl'];
107 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
109 $this->hashLevels
= isset( $info['hashLevels'] )
110 ?
$info['hashLevels']
112 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
113 ?
$info['deletedHashLevels']
115 $this->transformVia404
= !empty( $info['transformVia404'] );
116 $this->zones
= isset( $info['zones'] )
119 // Give defaults for the basic zones...
120 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
121 if ( !isset( $this->zones
[$zone] ) ) {
122 $this->zones
[$zone] = array(
123 'container' => "{$this->name}-{$zone}",
124 'directory' => '' // container root
131 * Get the file backend instance. Use this function wisely.
133 * @return FileBackend
135 public function getBackend() {
136 return $this->backend
;
140 * Get an explanatory message if this repo is read-only.
141 * This checks if an administrator disabled writes to the backend.
143 * @return string|bool Returns false if the repo is not read-only
145 public function getReadOnlyReason() {
146 return $this->backend
->getReadOnlyReason();
150 * Check if a single zone or list of zones is defined for usage
152 * @param $doZones Array Only do a particular zones
153 * @throws MWException
156 protected function initZones( $doZones = array() ) {
157 $status = $this->newGood();
158 foreach ( (array)$doZones as $zone ) {
159 $root = $this->getZonePath( $zone );
160 if ( $root === null ) {
161 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
168 * Take all available measures to prevent web accessibility of new deleted
169 * directories, in case the user has not configured offline storage
174 protected function initDeletedDir( $dir ) {
175 $this->backend
->secure( // prevent web access & dir listings
176 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
180 * Determine if a string is an mwrepo:// URL
185 public static function isVirtualUrl( $url ) {
186 return substr( $url, 0, 9 ) == 'mwrepo://';
190 * Get a URL referring to this repository, with the private mwrepo protocol.
191 * The suffix, if supplied, is considered to be unencoded, and will be
192 * URL-encoded before being returned.
194 * @param $suffix string|bool
197 public function getVirtualUrl( $suffix = false ) {
198 $path = 'mwrepo://' . $this->name
;
199 if ( $suffix !== false ) {
200 $path .= '/' . rawurlencode( $suffix );
206 * Get the URL corresponding to one of the four basic zones
208 * @param $zone String: one of: public, deleted, temp, thumb
209 * @return String or false
211 public function getZoneUrl( $zone ) {
216 return "{$this->url}/temp";
218 return false; // no public URL
220 return $this->thumbUrl
;
227 * Get the backend storage path corresponding to a virtual URL.
228 * Use this function wisely.
231 * @throws MWException
234 public function resolveVirtualUrl( $url ) {
235 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
236 throw new MWException( __METHOD__
.': unknown protocol' );
238 $bits = explode( '/', substr( $url, 9 ), 3 );
239 if ( count( $bits ) != 3 ) {
240 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
242 list( $repo, $zone, $rel ) = $bits;
243 if ( $repo !== $this->name
) {
244 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
246 $base = $this->getZonePath( $zone );
248 throw new MWException( __METHOD__
.": invalid zone: $zone" );
250 return $base . '/' . rawurldecode( $rel );
254 * The the storage container and base path of a zone
256 * @param $zone string
257 * @return Array (container, base path) or (null, null)
259 protected function getZoneLocation( $zone ) {
260 if ( !isset( $this->zones
[$zone] ) ) {
261 return array( null, null ); // bogus
263 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
267 * Get the storage path corresponding to one of the zones
269 * @param $zone string
270 * @return string|null Returns null if the zone is not defined
272 public function getZonePath( $zone ) {
273 list( $container, $base ) = $this->getZoneLocation( $zone );
274 if ( $container === null ||
$base === null ) {
277 $backendName = $this->backend
->getName();
278 if ( $base != '' ) { // may not be set
281 return "mwstore://$backendName/{$container}{$base}";
285 * Create a new File object from the local repository
287 * @param $title Mixed: Title object or string
288 * @param $time Mixed: Time at which the image was uploaded.
289 * If this is specified, the returned object will be an
290 * instance of the repository's old file class instead of a
291 * current file. Repositories not supporting version control
292 * should return false if this parameter is set.
293 * @return File|null A File, or null if passed an invalid Title
295 public function newFile( $title, $time = false ) {
296 $title = File
::normalizeTitle( $title );
301 if ( $this->oldFileFactory
) {
302 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
307 return call_user_func( $this->fileFactory
, $title, $this );
312 * Find an instance of the named file created at the specified time
313 * Returns false if the file does not exist. Repositories not supporting
314 * version control should return false if the time is specified.
316 * @param $title Mixed: Title object or string
317 * @param $options array Associative array of options:
318 * time: requested time for a specific file version, or false for the
319 * current version. An image object will be returned which was
320 * created at the specified time (which may be archived or current).
322 * ignoreRedirect: If true, do not follow file redirects
324 * private: If true, return restricted (deleted) files if the current
325 * user is allowed to view them. Otherwise, such files will not
327 * @return File|bool False on failure
329 public function findFile( $title, $options = array() ) {
330 $title = File
::normalizeTitle( $title );
334 $time = isset( $options['time'] ) ?
$options['time'] : false;
335 # First try the current version of the file to see if it precedes the timestamp
336 $img = $this->newFile( $title );
340 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
343 # Now try an old version of the file
344 if ( $time !== false ) {
345 $img = $this->newFile( $title, $time );
346 if ( $img && $img->exists() ) {
347 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
348 return $img; // always OK
349 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
356 if ( !empty( $options['ignoreRedirect'] ) ) {
359 $redir = $this->checkRedirect( $title );
360 if ( $redir && $title->getNamespace() == NS_FILE
) {
361 $img = $this->newFile( $redir );
365 if ( $img->exists() ) {
366 $img->redirectedFrom( $title->getDBkey() );
374 * Find many files at once.
376 * @param $items array An array of titles, or an array of findFile() options with
377 * the "title" option giving the title. Example:
379 * $findItem = array( 'title' => $title, 'private' => true );
380 * $findBatch = array( $findItem );
381 * $repo->findFiles( $findBatch );
384 public function findFiles( array $items ) {
386 foreach ( $items as $item ) {
387 if ( is_array( $item ) ) {
388 $title = $item['title'];
390 unset( $options['title'] );
395 $file = $this->findFile( $title, $options );
397 $result[$file->getTitle()->getDBkey()] = $file;
404 * Find an instance of the file with this key, created at the specified time
405 * Returns false if the file does not exist. Repositories not supporting
406 * version control should return false if the time is specified.
408 * @param $sha1 String base 36 SHA-1 hash
409 * @param $options array Option array, same as findFile().
410 * @return File|bool False on failure
412 public function findFileFromKey( $sha1, $options = array() ) {
413 $time = isset( $options['time'] ) ?
$options['time'] : false;
414 # First try to find a matching current version of a file...
415 if ( $this->fileFactoryKey
) {
416 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
418 return false; // find-by-sha1 not supported
420 if ( $img && $img->exists() ) {
423 # Now try to find a matching old version of a file...
424 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
425 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
426 if ( $img && $img->exists() ) {
427 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
428 return $img; // always OK
429 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
438 * Get an array or iterator of file objects for files that have a given
439 * SHA-1 content hash.
445 public function findBySha1( $hash ) {
450 * Get the public root URL of the repository
454 public function getRootUrl() {
459 * Get the URL of thumb.php
463 public function getThumbScriptUrl() {
464 return $this->thumbScriptUrl
;
468 * Returns true if the repository can transform files via a 404 handler
472 public function canTransformVia404() {
473 return $this->transformVia404
;
477 * Get the name of an image from its title object
479 * @param $title Title
482 public function getNameFromTitle( Title
$title ) {
484 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
485 $name = $title->getUserCaseDBKey();
486 if ( $this->initialCapital
) {
487 $name = $wgContLang->ucfirst( $name );
490 $name = $title->getDBkey();
496 * Get the public zone root storage directory of the repository
500 public function getRootDirectory() {
501 return $this->getZonePath( 'public' );
505 * Get a relative path including trailing slash, e.g. f/fa/
506 * If the repo is not hashed, returns an empty string
508 * @param $name string Name of file
511 public function getHashPath( $name ) {
512 return self
::getHashPathForLevel( $name, $this->hashLevels
);
516 * Get a relative path including trailing slash, e.g. f/fa/
517 * If the repo is not hashed, returns an empty string
519 * @param $suffix string Basename of file from FileRepo::storeTemp()
522 public function getTempHashPath( $suffix ) {
523 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
524 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
525 return self
::getHashPathForLevel( $name, $this->hashLevels
);
533 protected static function getHashPathForLevel( $name, $levels ) {
534 if ( $levels == 0 ) {
537 $hash = md5( $name );
539 for ( $i = 1; $i <= $levels; $i++
) {
540 $path .= substr( $hash, 0, $i ) . '/';
547 * Get the number of hash directory levels
551 public function getHashLevels() {
552 return $this->hashLevels
;
556 * Get the name of this repository, as specified by $info['name]' to the constructor
560 public function getName() {
565 * Make an url to this repo
567 * @param $query mixed Query string to append
568 * @param $entry string Entry point; defaults to index
569 * @return string|bool False on failure
571 public function makeUrl( $query = '', $entry = 'index' ) {
572 if ( isset( $this->scriptDirUrl
) ) {
573 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
574 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
580 * Get the URL of an image description page. May return false if it is
581 * unknown or not applicable. In general this should only be called by the
582 * File class, since it may return invalid results for certain kinds of
583 * repositories. Use File::getDescriptionUrl() in user code.
585 * In particular, it uses the article paths as specified to the repository
586 * constructor, whereas local repositories use the local Title functions.
588 * @param $name string
591 public function getDescriptionUrl( $name ) {
592 $encName = wfUrlencode( $name );
593 if ( !is_null( $this->descBaseUrl
) ) {
594 # "http://example.com/wiki/Image:"
595 return $this->descBaseUrl
. $encName;
597 if ( !is_null( $this->articleUrl
) ) {
598 # "http://example.com/wiki/$1"
600 # We use "Image:" as the canonical namespace for
601 # compatibility across all MediaWiki versions.
602 return str_replace( '$1',
603 "Image:$encName", $this->articleUrl
);
605 if ( !is_null( $this->scriptDirUrl
) ) {
606 # "http://example.com/w"
608 # We use "Image:" as the canonical namespace for
609 # compatibility across all MediaWiki versions,
610 # and just sort of hope index.php is right. ;)
611 return $this->makeUrl( "title=Image:$encName" );
617 * Get the URL of the content-only fragment of the description page. For
618 * MediaWiki this means action=render. This should only be called by the
619 * repository's file class, since it may return invalid results. User code
620 * should use File::getDescriptionText().
622 * @param $name String: name of image to fetch
623 * @param $lang String: language to fetch it in, if any.
626 public function getDescriptionRenderUrl( $name, $lang = null ) {
627 $query = 'action=render';
628 if ( !is_null( $lang ) ) {
629 $query .= '&uselang=' . $lang;
631 if ( isset( $this->scriptDirUrl
) ) {
632 return $this->makeUrl(
634 wfUrlencode( 'Image:' . $name ) .
637 $descUrl = $this->getDescriptionUrl( $name );
639 return wfAppendQuery( $descUrl, $query );
647 * Get the URL of the stylesheet to apply to description pages
649 * @return string|bool False on failure
651 public function getDescriptionStylesheetUrl() {
652 if ( isset( $this->scriptDirUrl
) ) {
653 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
654 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
660 * Store a file to a given destination.
662 * @param $srcPath String: source FS path, storage path, or virtual URL
663 * @param $dstZone String: destination zone
664 * @param $dstRel String: destination relative path
665 * @param $flags Integer: bitwise combination of the following flags:
666 * self::DELETE_SOURCE Delete the source file after upload
667 * self::OVERWRITE Overwrite an existing destination file instead of failing
668 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
669 * same contents as the source
670 * self::SKIP_LOCKING Skip any file locking when doing the store
671 * @return FileRepoStatus
673 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
674 $this->assertWritableRepo(); // fail out if read-only
676 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
677 if ( $status->successCount
== 0 ) {
685 * Store a batch of files
687 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
688 * @param $flags Integer: bitwise combination of the following flags:
689 * self::DELETE_SOURCE Delete the source file after upload
690 * self::OVERWRITE Overwrite an existing destination file instead of failing
691 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
692 * same contents as the source
693 * self::SKIP_LOCKING Skip any file locking when doing the store
694 * @throws MWException
695 * @return FileRepoStatus
697 public function storeBatch( array $triplets, $flags = 0 ) {
698 $this->assertWritableRepo(); // fail out if read-only
700 $status = $this->newGood();
701 $backend = $this->backend
; // convenience
703 $operations = array();
704 $sourceFSFilesToDelete = array(); // cleanup for disk source files
705 // Validate each triplet and get the store operation...
706 foreach ( $triplets as $triplet ) {
707 list( $srcPath, $dstZone, $dstRel ) = $triplet;
709 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
712 // Resolve destination path
713 $root = $this->getZonePath( $dstZone );
715 throw new MWException( "Invalid zone: $dstZone" );
717 if ( !$this->validateFilename( $dstRel ) ) {
718 throw new MWException( 'Validation error in $dstRel' );
720 $dstPath = "$root/$dstRel";
721 $dstDir = dirname( $dstPath );
722 // Create destination directories for this triplet
723 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
724 return $this->newFatal( 'directorycreateerror', $dstDir );
727 if ( $dstZone == 'deleted' ) {
728 $this->initDeletedDir( $dstDir );
731 // Resolve source to a storage path if virtual
732 $srcPath = $this->resolveToStoragePath( $srcPath );
734 // Get the appropriate file operation
735 if ( FileBackend
::isStoragePath( $srcPath ) ) {
736 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
739 if ( $flags & self
::DELETE_SOURCE
) {
740 $sourceFSFilesToDelete[] = $srcPath;
743 $operations[] = array(
747 'overwrite' => $flags & self
::OVERWRITE
,
748 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
752 // Execute the store operation for each triplet
753 $opts = array( 'force' => true );
754 if ( $flags & self
::SKIP_LOCKING
) {
755 $opts['nonLocking'] = true;
757 $status->merge( $backend->doOperations( $operations, $opts ) );
758 // Cleanup for disk source files...
759 foreach ( $sourceFSFilesToDelete as $file ) {
760 wfSuppressWarnings();
761 unlink( $file ); // FS cleanup
769 * Deletes a batch of files.
770 * Each file can be a (zone, rel) pair, virtual url, storage path.
771 * It will try to delete each file, but ignores any errors that may occur.
773 * @param $files array List of files to delete
774 * @param $flags Integer: bitwise combination of the following flags:
775 * self::SKIP_LOCKING Skip any file locking when doing the deletions
776 * @return FileRepoStatus
778 public function cleanupBatch( array $files, $flags = 0 ) {
779 $this->assertWritableRepo(); // fail out if read-only
781 $status = $this->newGood();
783 $operations = array();
784 foreach ( $files as $path ) {
785 if ( is_array( $path ) ) {
786 // This is a pair, extract it
787 list( $zone, $rel ) = $path;
788 $path = $this->getZonePath( $zone ) . "/$rel";
790 // Resolve source to a storage path if virtual
791 $path = $this->resolveToStoragePath( $path );
793 $operations[] = array( 'op' => 'delete', 'src' => $path );
795 // Actually delete files from storage...
796 $opts = array( 'force' => true );
797 if ( $flags & self
::SKIP_LOCKING
) {
798 $opts['nonLocking'] = true;
800 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
806 * Import a file from the local file system into the repo.
807 * This does no locking nor journaling and overrides existing files.
808 * This function can be used to write to otherwise read-only foreign repos.
809 * This is intended for copying generated thumbnails into the repo.
811 * @param $src string File system path
812 * @param $dst string Virtual URL or storage path
813 * @return FileRepoStatus
815 final public function quickImport( $src, $dst ) {
816 return $this->quickImportBatch( array( array( $src, $dst ) ) );
820 * Purge a file from the repo. This does no locking nor journaling.
821 * This function can be used to write to otherwise read-only foreign repos.
822 * This is intended for purging thumbnails.
824 * @param $path string Virtual URL or storage path
825 * @return FileRepoStatus
827 final public function quickPurge( $path ) {
828 return $this->quickPurgeBatch( array( $path ) );
832 * Deletes a directory if empty.
833 * This function can be used to write to otherwise read-only foreign repos.
835 * @param $dir string Virtual URL (or storage path) of directory to clean
838 public function quickCleanDir( $dir ) {
839 $status = $this->newGood();
840 $status->merge( $this->backend
->clean(
841 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
847 * Import a batch of files from the local file system into the repo.
848 * This does no locking nor journaling and overrides existing files.
849 * This function can be used to write to otherwise read-only foreign repos.
850 * This is intended for copying generated thumbnails into the repo.
852 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
853 * @return FileRepoStatus
855 public function quickImportBatch( array $pairs ) {
856 $status = $this->newGood();
857 $operations = array();
858 foreach ( $pairs as $pair ) {
859 list ( $src, $dst ) = $pair;
860 $operations[] = array(
863 'dst' => $this->resolveToStoragePath( $dst ),
866 $this->backend
->prepare( array( 'dir' => dirname( $dst ) ) );
868 $status->merge( $this->backend
->doOperations( $operations,
869 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
876 * Purge a batch of files from the repo.
877 * This function can be used to write to otherwise read-only foreign repos.
878 * This does no locking nor journaling and is intended for purging thumbnails.
880 * @param $paths Array List of virtual URLs or storage paths
881 * @return FileRepoStatus
883 public function quickPurgeBatch( array $paths ) {
884 $status = $this->newGood();
885 $operations = array();
886 foreach ( $paths as $path ) {
887 $operations[] = array(
889 'src' => $this->resolveToStoragePath( $path ),
890 'ignoreMissingSource' => true
893 $status->merge( $this->backend
->doOperations( $operations,
894 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
901 * Pick a random name in the temp zone and store a file to it.
902 * Returns a FileRepoStatus object with the file Virtual URL in the value,
903 * file can later be disposed using FileRepo::freeTemp().
905 * @param $originalName String: the base name of the file as specified
906 * by the user. The file extension will be maintained.
907 * @param $srcPath String: the current location of the file.
908 * @return FileRepoStatus object with the URL in the value.
910 public function storeTemp( $originalName, $srcPath ) {
911 $this->assertWritableRepo(); // fail out if read-only
913 $date = gmdate( "YmdHis" );
914 $hashPath = $this->getHashPath( $originalName );
915 $dstRel = "{$hashPath}{$date}!{$originalName}";
916 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
918 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
919 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
925 * Concatenate a list of files into a target file location.
927 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
928 * @param $dstPath String Target file system path
929 * @param $flags Integer: bitwise combination of the following flags:
930 * self::DELETE_SOURCE Delete the source files
931 * @return FileRepoStatus
933 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
934 $this->assertWritableRepo(); // fail out if read-only
936 $status = $this->newGood();
939 $deleteOperations = array(); // post-concatenate ops
940 foreach ( $srcPaths as $srcPath ) {
941 // Resolve source to a storage path if virtual
942 $source = $this->resolveToStoragePath( $srcPath );
943 $sources[] = $source; // chunk to merge
944 if ( $flags & self
::DELETE_SOURCE
) {
945 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
949 // Concatenate the chunks into one FS file
950 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
951 $status->merge( $this->backend
->concatenate( $params ) );
952 if ( !$status->isOK() ) {
956 // Delete the sources if required
957 if ( $deleteOperations ) {
958 $opts = array( 'force' => true );
959 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
962 // Make sure status is OK, despite any $deleteOperations fatals
963 $status->setResult( true );
969 * Remove a temporary file or mark it for garbage collection
971 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
972 * @return Boolean: true on success, false on failure
974 public function freeTemp( $virtualUrl ) {
975 $this->assertWritableRepo(); // fail out if read-only
977 $temp = "mwrepo://{$this->name}/temp";
978 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
979 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
982 $path = $this->resolveVirtualUrl( $virtualUrl );
984 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
988 * Copy or move a file either from a storage path, virtual URL,
989 * or FS path, into this repository at the specified destination location.
991 * Returns a FileRepoStatus object. On success, the value contains "new" or
992 * "archived", to indicate whether the file was new with that name.
994 * @param $srcPath String: the source FS path, storage path, or URL
995 * @param $dstRel String: the destination relative path
996 * @param $archiveRel String: the relative path where the existing file is to
997 * be archived, if there is one. Relative to the public zone root.
998 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
999 * that the source file should be deleted if possible
1000 * @return FileRepoStatus
1002 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1003 $this->assertWritableRepo(); // fail out if read-only
1005 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1006 if ( $status->successCount
== 0 ) {
1007 $status->ok
= false;
1009 if ( isset( $status->value
[0] ) ) {
1010 $status->value
= $status->value
[0];
1012 $status->value
= false;
1019 * Publish a batch of files
1021 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1022 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1023 * that the source files should be deleted if possible
1024 * @throws MWException
1025 * @return FileRepoStatus
1027 public function publishBatch( array $triplets, $flags = 0 ) {
1028 $this->assertWritableRepo(); // fail out if read-only
1030 $backend = $this->backend
; // convenience
1031 // Try creating directories
1032 $status = $this->initZones( 'public' );
1033 if ( !$status->isOK() ) {
1037 $status = $this->newGood( array() );
1039 $operations = array();
1040 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1041 // Validate each triplet and get the store operation...
1042 foreach ( $triplets as $i => $triplet ) {
1043 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1044 // Resolve source to a storage path if virtual
1045 $srcPath = $this->resolveToStoragePath( $srcPath );
1046 if ( !$this->validateFilename( $dstRel ) ) {
1047 throw new MWException( 'Validation error in $dstRel' );
1049 if ( !$this->validateFilename( $archiveRel ) ) {
1050 throw new MWException( 'Validation error in $archiveRel' );
1053 $publicRoot = $this->getZonePath( 'public' );
1054 $dstPath = "$publicRoot/$dstRel";
1055 $archivePath = "$publicRoot/$archiveRel";
1057 $dstDir = dirname( $dstPath );
1058 $archiveDir = dirname( $archivePath );
1059 // Abort immediately on directory creation errors since they're likely to be repetitive
1060 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1061 return $this->newFatal( 'directorycreateerror', $dstDir );
1063 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1064 return $this->newFatal( 'directorycreateerror', $archiveDir );
1067 // Archive destination file if it exists
1068 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1069 // Check if the archive file exists
1070 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1071 // unlinks the destination file if it exists. DB-based synchronisation in
1072 // publishBatch's caller should prevent races. In Windows there's no
1073 // problem because the rename primitive fails if the destination exists.
1074 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1075 $operations[] = array( 'op' => 'null' );
1078 $operations[] = array(
1081 'dst' => $archivePath
1084 $status->value
[$i] = 'archived';
1086 $status->value
[$i] = 'new';
1088 // Copy (or move) the source file to the destination
1089 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1090 if ( $flags & self
::DELETE_SOURCE
) {
1091 $operations[] = array(
1097 $operations[] = array(
1103 } else { // FS source path
1104 $operations[] = array(
1109 if ( $flags & self
::DELETE_SOURCE
) {
1110 $sourceFSFilesToDelete[] = $srcPath;
1115 // Execute the operations for each triplet
1116 $opts = array( 'force' => true );
1117 $status->merge( $backend->doOperations( $operations, $opts ) );
1118 // Cleanup for disk source files...
1119 foreach ( $sourceFSFilesToDelete as $file ) {
1120 wfSuppressWarnings();
1121 unlink( $file ); // FS cleanup
1122 wfRestoreWarnings();
1129 * Deletes a directory if empty.
1131 * @param $dir string Virtual URL (or storage path) of directory to clean
1134 public function cleanDir( $dir ) {
1135 $this->assertWritableRepo(); // fail out if read-only
1137 $status = $this->newGood();
1138 $status->merge( $this->backend
->clean(
1139 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1145 * Checks existence of a a file
1147 * @param $file string Virtual URL (or storage path) of file to check
1150 public function fileExists( $file ) {
1151 $result = $this->fileExistsBatch( array( $file ) );
1156 * Checks existence of an array of files.
1158 * @param $files Array: Virtual URLs (or storage paths) of files to check
1159 * @return array|bool Either array of files and existence flags, or false
1161 public function fileExistsBatch( array $files ) {
1163 foreach ( $files as $key => $file ) {
1164 $file = $this->resolveToStoragePath( $file );
1165 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1171 * Move a file to the deletion archive.
1172 * If no valid deletion archive exists, this may either delete the file
1173 * or throw an exception, depending on the preference of the repository
1175 * @param $srcRel Mixed: relative path for the file to be deleted
1176 * @param $archiveRel Mixed: relative path for the archive location.
1177 * Relative to a private archive directory.
1178 * @return FileRepoStatus object
1180 public function delete( $srcRel, $archiveRel ) {
1181 $this->assertWritableRepo(); // fail out if read-only
1183 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1187 * Move a group of files to the deletion archive.
1189 * If no valid deletion archive is configured, this may either delete the
1190 * file or throw an exception, depending on the preference of the repository.
1192 * The overwrite policy is determined by the repository -- currently LocalRepo
1193 * assumes a naming scheme in the deleted zone based on content hash, as
1194 * opposed to the public zone which is assumed to be unique.
1196 * @param $sourceDestPairs Array of source/destination pairs. Each element
1197 * is a two-element array containing the source file path relative to the
1198 * public root in the first element, and the archive file path relative
1199 * to the deleted zone root in the second element.
1200 * @throws MWException
1201 * @return FileRepoStatus
1203 public function deleteBatch( array $sourceDestPairs ) {
1204 $this->assertWritableRepo(); // fail out if read-only
1206 // Try creating directories
1207 $status = $this->initZones( array( 'public', 'deleted' ) );
1208 if ( !$status->isOK() ) {
1212 $status = $this->newGood();
1214 $backend = $this->backend
; // convenience
1215 $operations = array();
1216 // Validate filenames and create archive directories
1217 foreach ( $sourceDestPairs as $pair ) {
1218 list( $srcRel, $archiveRel ) = $pair;
1219 if ( !$this->validateFilename( $srcRel ) ) {
1220 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1221 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1222 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1225 $publicRoot = $this->getZonePath( 'public' );
1226 $srcPath = "{$publicRoot}/$srcRel";
1228 $deletedRoot = $this->getZonePath( 'deleted' );
1229 $archivePath = "{$deletedRoot}/{$archiveRel}";
1230 $archiveDir = dirname( $archivePath ); // does not touch FS
1232 // Create destination directories
1233 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1234 return $this->newFatal( 'directorycreateerror', $archiveDir );
1236 $this->initDeletedDir( $archiveDir );
1238 $operations[] = array(
1241 'dst' => $archivePath,
1242 // We may have 2+ identical files being deleted,
1243 // all of which will map to the same destination file
1244 'overwriteSame' => true // also see bug 31792
1248 // Move the files by execute the operations for each pair.
1249 // We're now committed to returning an OK result, which will
1250 // lead to the files being moved in the DB also.
1251 $opts = array( 'force' => true );
1252 $status->merge( $backend->doOperations( $operations, $opts ) );
1258 * Delete files in the deleted directory if they are not referenced in the filearchive table
1262 public function cleanupDeletedBatch( array $storageKeys ) {
1263 $this->assertWritableRepo();
1267 * Get a relative path for a deletion archive key,
1268 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1270 * @param $key string
1273 public function getDeletedHashPath( $key ) {
1275 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1276 $path .= $key[$i] . '/';
1282 * If a path is a virtual URL, resolve it to a storage path.
1283 * Otherwise, just return the path as it is.
1285 * @param $path string
1287 * @throws MWException
1289 protected function resolveToStoragePath( $path ) {
1290 if ( $this->isVirtualUrl( $path ) ) {
1291 return $this->resolveVirtualUrl( $path );
1297 * Get a local FS copy of a file with a given virtual URL/storage path.
1298 * Temporary files may be purged when the file object falls out of scope.
1300 * @param $virtualUrl string
1301 * @return TempFSFile|null Returns null on failure
1303 public function getLocalCopy( $virtualUrl ) {
1304 $path = $this->resolveToStoragePath( $virtualUrl );
1305 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1309 * Get a local FS file with a given virtual URL/storage path.
1310 * The file is either an original or a copy. It should not be changed.
1311 * Temporary files may be purged when the file object falls out of scope.
1313 * @param $virtualUrl string
1314 * @return FSFile|null Returns null on failure.
1316 public function getLocalReference( $virtualUrl ) {
1317 $path = $this->resolveToStoragePath( $virtualUrl );
1318 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1322 * Get properties of a file with a given virtual URL/storage path.
1323 * Properties should ultimately be obtained via FSFile::getProps().
1325 * @param $virtualUrl string
1328 public function getFileProps( $virtualUrl ) {
1329 $path = $this->resolveToStoragePath( $virtualUrl );
1330 return $this->backend
->getFileProps( array( 'src' => $path ) );
1334 * Get the timestamp of a file with a given virtual URL/storage path
1336 * @param $virtualUrl string
1337 * @return string|bool False on failure
1339 public function getFileTimestamp( $virtualUrl ) {
1340 $path = $this->resolveToStoragePath( $virtualUrl );
1341 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1345 * Get the sha1 of a file with a given virtual URL/storage path
1347 * @param $virtualUrl string
1348 * @return string|bool
1350 public function getFileSha1( $virtualUrl ) {
1351 $path = $this->resolveToStoragePath( $virtualUrl );
1352 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1356 return $tmpFile->getSha1Base36();
1360 * Attempt to stream a file with the given virtual URL/storage path
1362 * @param $virtualUrl string
1363 * @param $headers Array Additional HTTP headers to send on success
1364 * @return bool Success
1366 public function streamFile( $virtualUrl, $headers = array() ) {
1367 $path = $this->resolveToStoragePath( $virtualUrl );
1368 $params = array( 'src' => $path, 'headers' => $headers );
1369 return $this->backend
->streamFile( $params )->isOK();
1373 * Call a callback function for every public regular file in the repository.
1374 * This only acts on the current version of files, not any old versions.
1375 * May use either the database or the filesystem.
1377 * @param $callback Array|string
1380 public function enumFiles( $callback ) {
1381 $this->enumFilesInStorage( $callback );
1385 * Call a callback function for every public file in the repository.
1386 * May use either the database or the filesystem.
1388 * @param $callback Array|string
1391 protected function enumFilesInStorage( $callback ) {
1392 $publicRoot = $this->getZonePath( 'public' );
1393 $numDirs = 1 << ( $this->hashLevels
* 4 );
1394 // Use a priori assumptions about directory structure
1395 // to reduce the tree height of the scanning process.
1396 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1397 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1398 $path = $publicRoot;
1399 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1400 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1402 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1403 foreach ( $iterator as $name ) {
1404 // Each item returned is a public file
1405 call_user_func( $callback, "{$path}/{$name}" );
1411 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1413 * @param $filename string
1416 public function validateFilename( $filename ) {
1417 if ( strval( $filename ) == '' ) {
1420 return FileBackend
::isPathTraversalFree( $filename );
1424 * Get a callback function to use for cleaning error message parameters
1428 function getErrorCleanupFunction() {
1429 switch ( $this->pathDisclosureProtection
) {
1431 case 'simple': // b/c
1432 $callback = array( $this, 'passThrough' );
1434 default: // 'paranoid'
1435 $callback = array( $this, 'paranoidClean' );
1441 * Path disclosure protection function
1443 * @param $param string
1446 function paranoidClean( $param ) {
1451 * Path disclosure protection function
1453 * @param $param string
1456 function passThrough( $param ) {
1461 * Create a new fatal error
1463 * @return FileRepoStatus
1465 public function newFatal( $message /*, parameters...*/ ) {
1466 $params = func_get_args();
1467 array_unshift( $params, $this );
1468 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1472 * Create a new good result
1474 * @param $value null|string
1475 * @return FileRepoStatus
1477 public function newGood( $value = null ) {
1478 return FileRepoStatus
::newGood( $this, $value );
1482 * Checks if there is a redirect named as $title. If there is, return the
1483 * title object. If not, return false.
1486 * @param $title Title of image
1489 public function checkRedirect( Title
$title ) {
1494 * Invalidates image redirect cache related to that image
1495 * Doesn't do anything for repositories that don't support image redirects.
1498 * @param $title Title of image
1500 public function invalidateImageRedirect( Title
$title ) {}
1503 * Get the human-readable name of the repo
1507 public function getDisplayName() {
1508 // We don't name our own repo, return nothing
1509 if ( $this->isLocal() ) {
1512 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1513 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1517 * Returns true if this the local file repository.
1521 public function isLocal() {
1522 return $this->getName() == 'local';
1526 * Get a key on the primary cache for this repository.
1527 * Returns false if the repository's cache is not accessible at this site.
1528 * The parameters are the parts of the key, as for wfMemcKey().
1533 public function getSharedCacheKey( /*...*/ ) {
1538 * Get a key for this repo in the local cache domain. These cache keys are
1539 * not shared with remote instances of the repo.
1540 * The parameters are the parts of the key, as for wfMemcKey().
1544 public function getLocalCacheKey( /*...*/ ) {
1545 $args = func_get_args();
1546 array_unshift( $args, 'filerepo', $this->getName() );
1547 return call_user_func_array( 'wfMemcKey', $args );
1551 * Get an temporary FileRepo associated with this repo.
1552 * Files will be created in the temp zone of this repo and
1553 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1554 * It will have the same backend as this repo.
1556 * @return TempFileRepo
1558 public function getTempRepo() {
1559 return new TempFileRepo( array(
1560 'name' => "{$this->name}-temp",
1561 'backend' => $this->backend
,
1564 'container' => $this->zones
['temp']['container'],
1565 'directory' => $this->zones
['temp']['directory']
1568 'container' => $this->zones
['thumb']['container'],
1569 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1571 : $this->zones
['thumb']['directory'] . '/temp'
1574 'url' => $this->getZoneUrl( 'temp' ),
1575 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1576 'hashLevels' => $this->hashLevels
// performance
1581 * Get an UploadStash associated with this repo.
1583 * @return UploadStash
1585 public function getUploadStash() {
1586 return new UploadStash( $this );
1590 * Throw an exception if this repo is read-only by design.
1591 * This does not and should not check getReadOnlyReason().
1594 * @throws MWException
1596 protected function assertWritableRepo() {}
1600 * FileRepo for temporary files created via FileRepo::getTempRepo()
1602 class TempFileRepo
extends FileRepo
{
1603 public function getTempRepo() {
1604 throw new MWException( "Cannot get a temp repo from a temp repo." );